package ctrLayer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;

import modelLayer.*;

public class GraphCtr {
	
	private Date today;
	private GraphContainer gCont;

	public GraphCtr(){
		today = new Date();
		gCont = GraphContainer.getInstance();
	}
	
	public void addToGraph(String flavourName) throws NullPointerException{
		FlavourCtr fCtr = new FlavourCtr();
		Flavour f = fCtr.getFlavourObj(flavourName);
		if(f != null){
			gCont.addToDrawing(f);
		}else{
			throw new NullPointerException("The Flavour does not exist!");
		}
	}
	
	public void removeFromGraph(String flavourName){
		gCont.removeFromDrawing(flavourName);
	}
	
	public ArrayList<Flavour> drawThis(){
		return gCont.getFlavours();
	}
	
	public void clear(){
		gCont.clear();
	}
	
	public ArrayList<int[]> buildWeeks(Flavour f) throws NullPointerException{
		ArrayList<Sale> sales = f.getSales();
		Collections.sort(sales);
		Collections.reverse(sales);
		ArrayList<int[]> cords = new ArrayList<int[]>();
		
		Calendar cal = Calendar.getInstance();
		cal.setTime(today);
		
		for(Sale s : sales){
			Calendar cal2 = Calendar.getInstance();
			cal.setTime(s.getRealDate());
			if(s.getRealDate().before(today) && (cal.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) < 2){
				int amount = s.getAmount();
				//int date = getDays(s.getRealDate());
				int date = getWeek(s.getRealDate());
				int[] t = {amount, date};
				cords.add(t);
			}
		}
		return cords;
	}
	
	private int getWeek(Date date){
		int week = 0;
		Calendar cal = Calendar.getInstance();
		Calendar cal2 = Calendar.getInstance();
		cal.setTime(date);
		cal2.setTime(today);
		if(cal.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)){
			week = cal2.get(Calendar.WEEK_OF_YEAR) - cal.get(Calendar.WEEK_OF_YEAR);
			if(week == 0){
				week++;
			}
		}else{
			week = (52 - cal.get(Calendar.WEEK_OF_YEAR)) + cal2.get(Calendar.WEEK_OF_YEAR);
		}
		return week;
	}
}
